<template>
  <div class="edit">
    <div class="edit-title">
      <span class="title-1">用户管理</span> / <span class="title-2">{{ detailstatus ? '详情' : '编辑' }}</span>
    </div>
    <div class="edit-content">
      <div class="edit-content-title">用户基础信息</div>
      <div class="edit-content-form">
        <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="姓名">
                  <el-input v-model="formLabelAlign.realName" maxlength="16" class="set-form-wid" :disabled="detailstatus"
                    placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="年龄">
                  <el-input v-model="formLabelAlign.age" malength="3" class="set-form-wid" :disabled="detailstatus"
                    placeholder="请输入年龄"></el-input>
                </el-form-item>
                <el-form-item label="专业名称">
                  <el-input v-model="formLabelAlign.zhuanye" class="set-form-wid" placeholder="请输入专业名称" :disabled="detailstatus"></el-input>
                </el-form-item>
                <el-form-item label="省市县名称">
                  <template v-if="detailstatus">
                    <Address v-model="formLabelAlign.authorizeAddress" placeholder="请选择" clearable :level="1" :disabled="detailstatus"
                      class="set-form-wid"  />
                  </template>
                  <template v-else>
                    <Address v-model="formLabelAlign.authorizeAddress" placeholder="请选择" clearable :level="1"
                      class="set-form-wid" @input="(ids) => formLabelAlign.authorizeAddress = ids" />
                  </template>
                </el-form-item>
                <el-form-item label="角色">
                  <el-select v-model="formLabelAlign.roleId" placeholder="选择角色" multiple :disabled="detailstatus"
                    filterable clearable class="set-form-wid">
                    <el-option-group v-for="group in roleTreeData" :key="group.id" :label="group.fullName +
                      (group.num ? '【' + group.num + '】' : '')
                      ">
                      <el-option v-for="item in group.children" :key="group.id + item.id" :label="item.fullName"
                        :value="item.id">
                      </el-option>
                    </el-option-group>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="联系电话">
                  <el-input v-model="formLabelAlign.mobilePhone" class="set-form-wid" maxlength="11" :disabled="detailstatus"
                    placeholder="请输入联系电话"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="formLabelAlign.email" class="set-form-wid" placeholder="请输入邮箱" :disabled="detailstatus"
                    maxlength="32"></el-input>
                </el-form-item>
                <el-form-item label="职称">
                  <el-input v-model="formLabelAlign.zhicheng" class="set-form-wid" placeholder="请输入职称" :disabled="detailstatus"></el-input>
                </el-form-item>
                <el-form-item label="单位性质" style="width: 300px;">
                  <!-- <el-input v-model="formLabelAlign.unitNature" class="set-form-wid" placeholder="请输入单位性质"></el-input> -->
                  <el-select
                    v-model="formLabelAlign.unitNature"
                    placeholder="请选择单位性质"
                    :style="{ width: '100%' }"
                    :disabled="detailstatus"
                  >
                    <el-option
                      v-for="(item, index) in unitNatureOptions"
                      :key="index"
                      :label="item.fullName"
                      :value="item.enCode"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="性别">
                  <el-select v-model="formLabelAlign.gender" placeholder="请选择性别" label-width="80px" :disabled="detailstatus"
                    class="set-form-wid">
                    <el-option v-for="item in genderTreeData" :key="item.enCode" :label="item.fullName"
                      :value="item.enCode" />
                  </el-select>
                </el-form-item>
                <el-form-item label="职业">
                  <el-input v-model="formLabelAlign.zhiye" class="set-form-wid" placeholder="请输入职业" :disabled="detailstatus"></el-input>
                </el-form-item>
                <el-form-item label="参加工作时间">
                  <el-date-picker v-model="formLabelAlign.entryDate" type="date" placeholder="选择日期" :disabled="detailstatus"
                    value-format="timestamp" class="set-form-wid">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="单位级别"  style="width: 300px;">
                  <!-- <el-input v-model="formLabelAlign.unitLevel" class="set-form-wid" placeholder="请输入单位级别"></el-input> -->
                  <el-select
                    v-model="formLabelAlign.unitLevel"
                    placeholder="请选择单位级别"
                    :style="{ width: '100%' }"
                    :disabled="detailstatus"
                  >
                    <el-option
                      v-for="(item, index) in unitLevelOptions"
                      :key="index"
                      :label="item.fullName"
                      :value="item.enCode"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template v-if="detailstatus">
        <div class="edit-content-title title-top">学习记录</div>
        <div class="edit-study">
          <ul>
            <li :class="isOk ? 'active-study' : ''" @click="changeItem">
              专题培训记录
            </li>
            <li :class="!isOk ? 'active-study' : ''" @click="changeItem">
              考试记录
            </li>
          </ul>
          <div v-if="isOk">
            <!-- 专题培训记录 -->
            <el-table :data="tableTrainDataList" :header-cell-style="{
              backgroundColor: '#F6F8FC',
              color: '#606266',
            }" style="width: 100%; margin-bottom: 100px">
              <el-table-column label="培训开始时间" width="250" align="center" >
                <template slot-scope="scope">{{ scope.row.startDatetime }}</template>
              </el-table-column>
              <el-table-column prop="ztmc" label="专题名称" width="250">
                <template slot-scope="scope">{{ scope.row.name }}</template>
              </el-table-column>
              <el-table-column prop="examScore" label="技能考试分数" width="250">
                <template slot-scope="scope">
                  <div v-if="scope.row.examScore > 80">{{ scope.row.examScore }}</div>
                  <div v-else style="color: red">{{ scope.row.examScore }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="theoryScore" label="理论考试分数" >
                <template slot-scope="scope">
                  <div v-if="scope.row.theoryScore > 80">{{ scope.row.theoryScore }}</div>
                  <div v-else style="color: red">{{ scope.row.theoryScore }}</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else>
            <!-- 考试记录 -->
            <el-table :data="tableExamDataList" :header-cell-style="{
              backgroundColor: '#F6F8FC',
              color: '#606266',
            }" style="width: 100%; margin-bottom: 100px">
              <el-table-column label="考试时间" width="250" align="center" >
                <template slot-scope="scope">{{ scope.row.startTime }}</template>
              </el-table-column>
              <el-table-column prop="jjsj" label="考试名称" width="250">
                <template slot-scope="scope">{{ scope.row.examName }}</template>
              </el-table-column>
              <el-table-column prop="fs" label="分数">
                <template slot-scope="scope">
                  <div v-if="scope.row.myScore < 80" style="color: red">
                    {{ scope.row.examTask.myScore }}
                  </div>
                  <div v-else style="color: #536387">{{ scope.row.myScore }}</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </template> 
    </div>
    <div class="edit-footer"  v-if="!detailstatus">
      <el-button type="primary" @click="submitForm('formLabelAlign')">确定</el-button>
    </div>
  </div>
</template>
<script>
import { getRoleByOrganize } from "@/api/permission/role";
import { editUser } from "@/api/userManagerment";
import { getUserInfo } from "@/api/home";
import { myExamListTask, getMySubjectList } from "@/api/exam";
export default {
  data() {
    return {
      detailstatus: false,
      detailstatusNew: false,
      labelPosition: "top",
      formLabelAlign: {
        account: "",         // 账号
        code: "",            // 工号
        realName: "",        // 姓名
        age: "",             // 年龄
        zhuanye: "",         // 专业名称
        areaId: [],          // 省市县--真
        authorizeAddress: [],// 省市县
        roleId: [],          // 角色ID
        mobilePhone: "",     // 手机
        email: "",           // 邮箱
        zhicheng: "",        // 职称
        unitNature: "",      // 单位性质
        gender: "",          // 性别
        zhiye: "",           // 职业
        entryDate: null,     // 参加工作时间
        unitLevel: "",       // 单位级别
      },
      saveId: -1,
      isOk: true,
      roleTreeData: [],
      genderTreeData: [],
      unitNatureOptions: [],
      unitLevelOptions: [],
      tableTrainDataList: [],
      tableExamDataList: [],
      currentPage: 1,
      pageSize: 100,
    };
  },
  created() {
    this.saveId = this.$route.query.id;
    this.detailstatusNew = this.$route.query.detailStatus;
    this.loadZD();
    this.getUnitNatureOptions();
    this.getUnitLevelOptions();
  },
  mounted() {
    this.$forceUpdate();
    this.loadgetUserInfo();
  },
  watch: {
    detailstatusNew() {
      this.detailstatus = Boolean(this.detailstatusNew);
    }
  },
  methods: {
    // 获取培训数据
    getTrainList() {
      getMySubjectList({
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        creatorUserId: this.formLabelAlign.id
      }).then(res => {
        if (res.code == 200) {
          this.tableTrainDataList = res.data.list;
        }
      })
    },
    // 获取考试记录(我的考试)数据
    getExamList() {
      myExamListTask({
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        creatorUserId: this.formLabelAlign.id,
        categoryId: 4
      }).then((res) => {
        if(res.code === 200){
          this.tableExamDataList = res.data.list;
        }
      });
    },
    loadgetUserInfo() {
      getUserInfo(this.saveId)
        .then((res) => {
          if (res.data) {
            this.formLabelAlign = res.data;
            // roleId 是数组
            this.formLabelAlign.roleId = Array.isArray(res.data.roleId) 
              ? res.data.roleId 
              : (res.data.roleId ? res.data.roleId.split(',') : []);
            // 处理地区
            this.formLabelAlign.authorizeAddress = !this.formLabelAlign.areaId ? [] : this.formLabelAlign.areaId.split(',');
            // 如果有生日字段，计算年龄
            if (this.formLabelAlign.birthday) {
              const birthDate = new Date(this.formLabelAlign.birthday);
              const today = new Date();
              let age = today.getFullYear() - birthDate.getFullYear();
              const monthDiff = today.getMonth() - birthDate.getMonth();
              // 如果今年还没过生日，年龄减1
              if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                age--;
              }
              this.formLabelAlign.age = age.toString();
            }

            // 加载数据
            this.getExamList();
            this.getTrainList();
          }
        })
        .catch((e) => {
          this.$message.error("获取用户信息失败");
        });
    },
    // 获取数据字典：单位性质
    getUnitNatureOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "EnterpriseNature",
        })
        .then((res) => {
          this.unitNatureOptions = res;
        });
    },
    // 获取数据字典：单位级别
    getUnitLevelOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "EnterpriseGrade",
        })
        .then((res) => {
          this.unitLevelOptions = res;
        });
    },
    changeItem() {
      this.isOk = !this.isOk;
    },
    submitForm(formName) {
      this.formLabelAlign.roleId = this.formLabelAlign.roleId.toString();
      // 处理地区
      if (this.formLabelAlign.authorizeAddress.length > 0) {
        let areaId = this.formLabelAlign.authorizeAddress;
        this.formLabelAlign.areaId  = areaId.toString();
      }
      delete this.formLabelAlign.authorizeAddress;
      editUser(this.saveId, this.formLabelAlign)
        .then((res) => {
          this.$router.go(-1);
          this.$message({
            message: "更新成功",
            type: "success",
          });
        })
        .catch((e) => {
          this.$message.error("更新失败");
        });
    },
    loadZD() {
      // 获取性别
      this.genderTreeData = [
        {
          enCode: "1",
          fullName: "男"
        },
        {
          enCode: "2",
          fullName: "女"
        }
      ];
      getRoleByOrganize().then((res) => {
        this.roleTreeData = res.data.list.filter(
          (o) => o.children && Array.isArray(o.children) && o.children.length
        );
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.title-top {
  margin-top: 32px;
}

.edit {
  box-sizing: border-box;
  height: 100%;
  position: relative;

  .edit-title {
    font-weight: 500;
    font-size: 19px;
    color: #536387;
    line-height: 29px;
    text-align: left;
    font-style: normal;

    .title-1 {
      color: #536387;
      padding-right: 11px;
    }

    .title-2 {
      padding-left: 11px;
      color: #323232;
    }
  }

  .edit-content {
    width: 100%;
    height: auto;
    background: #fff;
    box-sizing: border-box;
    padding: 32px;
    margin-top: 32px;

    .edit-content-title {
      font-size: 21px;
      width: 100%;
      height: 39px;
      line-height: 21px;
      position: relative;
      padding-left: 11px;
      border-bottom: 1px solid #e2e7f5;

      &:before {
        content: "";
        position: absolute;
        width: 4px;
        height: 21px;
        top: 0;
        left: 0;
        background: #2265ee;
        display: inline-block;
      }
    }

    .edit-content-form {
      margin-top: 32px;
    }
  }

  .edit-footer {
    width: 100%;
    height: 103px;
    position: fixed;
    bottom: 0;
    left: 0;
    background: #fff;
    text-align: right;
    line-height: 103px;

    .el-button {
      width: 100px;
      height: 40px;
      margin-right: 32px;
      background: #2265ee;
      border-box: 1px solid #2265ee;

      &:active {
        opacity: 0.8;
      }
    }
  }
}

.edit-study {
  margin-top: 32px;

  ul {
    list-style: none;
    font-size: 19px;
    color: #0d162a;

    li {
      width: 176px;
      height: 53px;
      display: inline-block;
      line-height: 53px;
      text-align: center;
      cursor: pointer;
    }
  }
}

.active-study {
  background-color: #f6f8fc;
  border-radius: 5px 133px 0px 0px;
}

::v-deep .el-icon-my-zs {
  background: url("../../assets/images/zs1.png") no-repeat;
  width: 20px;
  height: 20px;
}

::v-deep .el-icon-my-zs:before {
  content: "替";
  font-size: 20px;
  visibility: hidden;
}

::v-deep .el-icon-my-zs {
  font-size: 18px;
}

::v-deep .el-icon-my-zs:before {
  content: "\e611";
}

.set-form-wid {
  width: 300px !important;
}
</style>
